﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;

namespace Dominio {
    public static class Helper {
        public static void IncluiPropriedade(object obj, string nomePropriedade, object valor) {
            PropertyInfo property = obj.GetType().GetProperty(nomePropriedade, BindingFlags.Public | BindingFlags.Public | BindingFlags.Instance);
            if (property != null) {
                property.SetValue(obj, valor, null);
            } else {
                FieldInfo field = obj.GetType().GetField(nomePropriedade, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
                field.SetValue(obj, valor);
            }
        }
        public static object ObtemPropriedade(object obj, string nomePropriedade) {
            PropertyInfo property = obj.GetType().GetProperty(nomePropriedade, BindingFlags.Public | BindingFlags.Public | BindingFlags.Instance);
            if (property != null) {
                return property.GetValue(obj, null);//, BindingFlags.Public | BindingFlags.Public | BindingFlags.Instance);
            } else {
                FieldInfo field = obj.GetType().GetField(nomePropriedade, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
                return field.GetValue(obj);
            }
        }
        //public static void SetPropertyValue(object obj, string nomePropriedade, object valor) {
        //    PropertyInfo property = obj.GetType().GetProperty(nomePropriedade, BindingFlags.Public | BindingFlags.Public | BindingFlags.Instance);
        //    property.SetValue(obj, valor, null);
        //}

        //public static object GetFieldValue(object obj, string nomePropriedade) {
        //    FieldInfo property = obj.GetType().GetField(nomePropriedade, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

        //    return property.GetValue(obj);
        //}

        //public static void SetFieldValue(object obj, string nomePropriedade, object valor) {
        //    FieldInfo property = obj.GetType().GetField(nomePropriedade, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

        //    property.SetValue(obj, valor);
        //}

        public static string GetDescription(this Enum en) {
            Type type = en.GetType();

            MemberInfo[] memInfo = type.GetMember(en.ToString());

            if (memInfo != null && memInfo.Length > 0) {
                object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

                if (attrs != null && attrs.Length > 0) {
                    return ((DescriptionAttribute)attrs[0]).Description;
                }
            }

            return en.ToString();
        }
    }
}
